package com.itheima.interception;


import com.itheima.holder.AdminLocal;
import com.itheima.pojo.UmsAdmin;
import com.itheima.util.JWTUtil;
import io.jsonwebtoken.Claims;
import jdk.nashorn.internal.ir.CallNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头获取token
        String header = request.getHeader("Authorization");
        String token = header.replace("undefined", "");
        log.info("本次访问路径是{}", request.getRequestURI());
        //2.判断token是否有效
        boolean flag = JWTUtil.verifyToken(token);
        if (!flag) {
            //2.1无效返回状态码401,为什么返回401,应该是前台收到401,会跳转登录
           response.setStatus(401);
            //2.2拦截
            return flag;
        }
        //3.有效将数据存入Threadlocal,就放行
        Claims claims = JWTUtil.getClaims(token);
        Long id1 = claims.get("id", Long.class);
        String username1 = claims.get("username", String.class);

        System.out.println();

        UmsAdmin admin = new UmsAdmin();

        admin.setId(id1);

        admin.setUsername(username1);
        AdminLocal.set(admin);

        return flag;
    }

    //大量用户访问时,Threadlocal可能会内存溢出,我们这里访问结束对threadlocal清空
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminLocal.remove();
    }
}
